package sorting;

import edu.princeton.cs.algs4.StdIn;

/**
 * 选择排序算法类的
 */
public class Selection {
    //选择排序算法具体实现
    public static void sort(Comparable[] a) {
        int N=a.length;
        for (int i = 0; i < N; i++) {
            int min=i;
            for (int j = i+1; j < N; j++) {
                if(less(a[j],a[min]))min=j;
            }
            exch(a,i,min);
        }
    }

    //less 对元素进行比较,是否v比w小
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }

    //exch 将元素交换位置
    private static void exch(Comparable[] a, int i, int j) {
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    //在单行中打印数组
    private static void show(Comparable[] a) {
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + " ");
        }
        System.out.println();
    }

    //测试数组元素是否有序 从小到大
    public static boolean isSorted(Comparable[] a) {
        for (int i = 1; i < a.length; i++) {
            if (less(a[i], a[i - 1])) return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String[] a = StdIn.readAllStrings();
        sort(a);
        assert isSorted(a);
        show(a);
    }

}
